package com.xiubai.appforpda.activitys;

import android.app.Dialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.SoundPool;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.nfc.tech.NfcA;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.xiubai.appforpda.App;
import com.xiubai.appforpda.R;
import com.xiubai.appforpda.db.DatabaseUtils;
import com.xiubai.appforpda.entity.BaseEntity;
import com.xiubai.appforpda.entity.MYSQLNCReturnBean;
import com.xiubai.appforpda.entity.SQLDevicesReturnBean;
import com.xiubai.appforpda.entity.SQLMainPamInventBean;
import com.xiubai.appforpda.entity.SQLNCGetUseBean;
import com.xiubai.appforpda.entity.SQLOrgPersonBean;
import com.xiubai.appforpda.entity.SQLOrgStructureBean;
import com.xiubai.appforpda.entity.SQLPamAssetBean;
import com.xiubai.appforpda.entity.SQLPamInvenBean;
import com.xiubai.appforpda.entity.SQLPamLocationBean;
import com.xiubai.appforpda.entity.SQLPamStatusBean;
import com.xiubai.appforpda.entity.WebAssetEntity;
import com.xiubai.appforpda.entity.WebLocationEntity;
import com.xiubai.appforpda.entity.WebMainPamInventEntity;
import com.xiubai.appforpda.entity.WebNCGetUseEntity;
import com.xiubai.appforpda.entity.WebOrgStructureEntity;
import com.xiubai.appforpda.entity.WebPamInventEntity;
import com.xiubai.appforpda.entity.WebPamStatusEntity;
import com.xiubai.appforpda.entity.WebPersonEntity;
import com.xiubai.appforpda.event.CloseEvent;
import com.xiubai.appforpda.jack.utils.AppConstants;
import com.xiubai.appforpda.jack.utils.JsonParser;
import com.xiubai.appforpda.jack.utils.SharedPreferenceTool;
import com.xiubai.appforpda.jack.utils.TextRecord;
import com.xiubai.appforpda.jack.utils.Trace;
import com.xiubai.appforpda.jack.utils.Utils;
import com.xiubai.appforpda.jack.utils.WebServiceDataUtils;
import com.xiubai.appforpda.nfc.NdefMessageParser;
import com.xiubai.appforpda.nfc.NfcUtil;
import com.xiubai.appforpda.nfc.TagViewer;
import com.xiubai.appforpda.nfc.record.ParsedNdefRecord;
import com.xiubai.appforpda.utils.CardManager;
import com.xiubai.appforpda.utils.ClickUtil;
import com.xiubai.appforpda.utils.DisplayUtil;
import com.xiubai.appforpda.utils.ErrorMsgException;
import com.xiubai.appforpda.utils.NfcUtils;
import com.xiubai.appforpda.utils.nfctool.NfcDemoActivity;
import com.xiubai.appforpda.webutils.WebServiceHelper;
import com.xiubai.appforpda.widget.CustomDialog;
import com.xiubai.appforpda.widget.CustomDialogListener;
import com.xiubai.appforpda.widget.DeptDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.ksoap2.serialization.SoapObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;

import static android.widget.Toast.LENGTH_LONG;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private View btn_setting;
    private View btn_test;
    private View btn_test_in;
//    private Handler handler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what) {
//                case GET_ORG:
//                    String url = (String) msg.obj;
//                    callWS(url);
//                    break;
//            }
//        }
//    };
    /*
     * 高频NFC适配器
     */
    private NfcAdapter nfcAdapter;
    private SoundPool soundPool;

    /**
     * 扫描跳转Activity RequestCode
     */
    public static final int REQUEST_CODE = 111;
    /**
     * 选择系统图片Request Code
     */
    public static final int REQUEST_IMAGE = 112;

    /**
     * 请求CAMERA权限码
     */
    public static final int REQUEST_CAMERA_PERM = 101;
//    private static final int GET_ORG = 0;
//    private int count = 0;
    private View btn_test_scan;
    private View btn_setting_login;
    private TextView tv_promt;

    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private NdefMessage mNdefPushMessage;





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initSound();
        initData();
        Trace.d("reg");
        EventBus.getDefault().register(this);


        initNfc();

    }

    private void initNfc() {
        mAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mAdapter == null) {
//            finish();
            return;
        }

        mPendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        mNdefPushMessage = new NdefMessage(new NdefRecord[] { NfcUtil.newTextRecord(
                "Message from NFC Reader :-)", Locale.ENGLISH, true) });
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CloseEvent event) {
        Trace.d("mainac   finish");
        finish();
        /* Do something */
    }


    @Override
    public void onStop() {
        super.onStop();
        Trace.d("unreg");

    }

    private void initData() {
        //nfc初始化设置
        AppConstants.IP_ADDRESS = SharedPreferenceTool.getInstance().getString(AppConstants.IP, "");
        AppConstants.PORT_ADDRESS = SharedPreferenceTool.getInstance().getString(AppConstants.PORT, "");
        Trace.d("app_ip=" + AppConstants.IP_ADDRESS);
        Trace.d("app_port=" + AppConstants.PORT_ADDRESS);
        SharedPreferenceTool.getInstance().saveString(AppConstants.USER, "0805000002");
    }

    @Override
    protected void onResume() {
        super.onResume();
//        getData();
        //开启前台调度系统
        //设定intentfilter和tech-list。如果两个都为null就代表优先接收任何形式的TAG action。也就是说系统会主动发TAG intent。
//        if (NfcUtils.mNfcAdapter != null) {
//            NfcUtils.mNfcAdapter.enableForegroundDispatch(this, NfcUtils.mPendingIntent, NfcUtils.mIntentFilter, NfcUtils.mTechList);
//        }

        if (mAdapter != null) {
            if (!mAdapter.isEnabled()) {
            }
            mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
            mAdapter.enableForegroundNdefPush(this, mNdefPushMessage);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
//        if (NfcUtils.mNfcAdapter != null) {
//            NfcUtils.mNfcAdapter.disableForegroundDispatch(this);
//        }

        if (mAdapter != null) {
            mAdapter.disableForegroundDispatch(this);
            mAdapter.disableForegroundNdefPush(this);
        }
    }


    //在onNewIntent中处理由NFC设备传递过来的intent
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Trace.d("--------------NFC-------------");
        // 读取
//        processIntent(intent);
        //调用工具方法，读取NFC数据
        try {
            resolveIntent(intent);
        } catch (Throwable e) {
        }
    }



    private List<Tag> mTags = new ArrayList<>();
    public void resolveIntent(Intent intent) {
        mTags.clear();
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            } else {
                // Unknown tag type   未知的标签类型
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                byte[] payload = NfcUtil.dumpTagData(tag).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
                msgs = new NdefMessage[] { msg };
                mTags.add(tag);
            }
            // 设置视图
//            buildTagViews(msgs);
//            List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);

            String idsDec = NfcUtil.getIdsHex(mTags); // 01 332959878  05 331880134
            String str = "getIdsDec="+ idsDec;
            Trace.d(str);
//            String hexStr = Integer.toHexString(Integer.parseInt(idsDec));// idsDec.replace(" ","");
            doLogin(idsDec.replace(" ",""));
        }
    }



    @Override
    protected void onDestroy() {
        mAdapter = null;
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    /*
     *初始化声音资源
     */
    private void initSound() {
        soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
        soundPool.load(this, R.raw.beep, 1);
    }

    private void initView() {
        btn_test = findViewById(R.id.btn_test);
        btn_setting_login = findViewById(R.id.btn_setting_login);
        btn_test_in = findViewById(R.id.btn_test_in);
        btn_setting = findViewById(R.id.btn_setting);
        btn_test_scan = findViewById(R.id.btn_test_scan);
        tv_promt = (TextView) findViewById(R.id.tv_promt);
        tv_promt.setOnClickListener(this);
        btn_setting.setOnClickListener(this);
        btn_test_scan.setOnClickListener(this);
        btn_setting_login.setOnClickListener(this);
        btn_test.setOnClickListener(this);
        btn_test_in.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if(ClickUtil.isFastDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_test_in:
//                callWS2();
//                Message message = Message.obtain();
//                message.what = 0;
//                message.obj = AppConstants.GET_ORG_DEPT;
//                handler.sendMessage(message);
//                Intent intent1 = new Intent(getApplication(), CaptureActivity.class);
//                startActivityForResult(intent1, REQUEST_CODE);
                break;
            case R.id.btn_setting_login:
                Intent intent8 = new Intent(MainActivity.this, TestLoginActivity.class);
                startActivity(intent8);
                break;
            case R.id.btn_setting:
                Intent intent = new Intent(MainActivity.this, SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_test:
//                Intent intent2 = new Intent(MainActivity.this, HomeActivity.class);
//                startActivity(intent2);
//                callWS();
               /* String json = "{\n" +
                        "\t'billcode': 'ZCPD201811200002',\n" +
                        "\t'assetcode': '201808060003',\n" +
                        "\t'assetname': 'sss',\n" +
                        "\t'usercodeh': '0805000004',\n" +
                        "\t'loccodeh': '03',\n" +
                        "\t'deptcodeh': '1001A2100000000000MV',\n" +
                        "\t'stacodeh': '01',\n" +
                        "\t'operator': '0805000004',\n" +
                        "\t'bill_status': 'Y'\n" +
                        "}";
                SQLMainPamInventBean bean = JsonParser.deserializeByJson(json, SQLMainPamInventBean.class);
                callGetUseWs(bean);*/
                List<SQLMainPamInventBean> sqlMainPamInventBeans = DatabaseUtils.getHelper().queryAll(SQLMainPamInventBean.class);
                Trace.d(">>>>>>" +sqlMainPamInventBeans.size());
//                DatabaseUtils.getHelper().update(SQLOrgPersonBean.class, "deptcode", "02", "psnname", "aabb");
                break;
            case R.id.btn_test_scan:
                Intent intent4 = new Intent(MainActivity.this, CaptureActivity.class);
                startActivityForResult(intent4, REQUEST_CODE);
//                callWS();
                break;
            case R.id.tv_promt:
//                TagViewer.actionStart(this);
//                doLogin("13c816c6");
//                doLogin("13d89086");
                break;
        }
    }

    private void testDb() {
        Trace.d("start time = " + System.currentTimeMillis());
        /*ArrayList<SQLPamInvenBean> list = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            SQLPamInvenBean assetBean = new SQLPamInvenBean();
            assetBean.memo = "aaaa" + i;
            list.add(assetBean);
        }
        DatabaseUtils.getHelper().saveAll(list);*/
        Trace.d("end time = " + System.currentTimeMillis());
    }

    private void callGetUseWs(final SQLMainPamInventBean bean) {
        //通过工具类调用WebService接口
        LinkedHashMap<String, String> value = WebServiceDataUtils.postCheckParameterData(bean);
        WebServiceHelper.callWebService(WebServiceHelper.WEB_URL, AppConstants.METHOD_NAME, value, new WebServiceHelper.WebServiceCallBack() {
            @Override
            public void callBack(SoapObject result) {
                Trace.d("result==" + result);
                if (result != null) {
                    String json = result.getProperty(0).toString();
                    Trace.d("json====" + json);
                    BaseEntity assetBean = JsonParser.deserializeByJson(json, BaseEntity.class);
                    if (assetBean != null) {
                        if (assetBean.isSuccess()) {
                        } else {
                        }
                    }
                }

            }
        });
    }


//    private void callWS(String url) {
//        Trace.d("url====" + url);
//        //通过工具类调用WebService接口
//        LinkedHashMap<String, String> value = WebServiceDataUtils.getParameterData(url, "1=1");
//        WebServiceHelper.callWebService(WebServiceHelper.WEB_URL, AppConstants.METHOD_NAME, value, new WebServiceHelper.WebServiceCallBack() {
//            @Override
//            public void callBack(SoapObject result) {
//                Trace.d("result==" + result);
//                if (result != null) {
//                    String json = result.getProperty(0).toString();
//                    Trace.d("json====" + json);
//                    BaseEntity assetBean = JsonParser.deserializeByJson(json, BaseEntity.class);
//                    if (assetBean != null) {
//                        if (assetBean.isSuccess()) {
//                            // do something
//                            Trace.d("成功!");
//                            count++;
//                            Message message = Message.obtain();
//                            message.what = 0;
//                            switch (count) {
//                                case 1:
//                                    WebOrgStructureEntity webOrgStructureEntity = JsonParser.deserializeByJson(json, WebOrgStructureEntity.class);
//                                    DatabaseUtils.getHelper().clear(SQLOrgStructureBean.class);
//                                    DatabaseUtils.getHelper().saveAll(webOrgStructureEntity.getV_org_dept());
//                                    message.obj = AppConstants.GET_PERSON;
//                                    break;
//                                case 2:
//                                    WebPersonEntity webPersonEntity = JsonParser.deserializeByJson(json, WebPersonEntity.class);
//                                    DatabaseUtils.getHelper().clear(SQLOrgPersonBean.class);
//                                    DatabaseUtils.getHelper().saveAll(webPersonEntity.getOrg_psn());
//                                    message.obj = AppConstants.GET_PAM_LOCATION;
//                                    break;
//                                case 3:
//                                    WebLocationEntity webLocationEntity = JsonParser.deserializeByJson(json, WebLocationEntity.class);
//                                    DatabaseUtils.getHelper().clear(SQLPamLocationBean.class);
//                                    DatabaseUtils.getHelper().saveAll(webLocationEntity.getPam_loc());
//                                  break;
//
//                            }
//                            if (count >= 8) {
//                                return;
//                            }
//                            handler.sendMessage(message);
//                        } else {
//                            Toast.makeText(MainActivity.this, "失败" + assetBean.status + "原因" + assetBean.msg, Toast.LENGTH_SHORT).show();
//                        }
//                    } else {
//                        Toast.makeText(MainActivity.this, "检查json格式" + json, Toast.LENGTH_SHORT).show();
//                    }
//                }else {
//                    Toast.makeText(MainActivity.this, "没有返回", Toast.LENGTH_SHORT).show();
//                }
//
//            }
//        });
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    Trace.d("result" + result);
                    Toast.makeText(this, "解析结果:" + result, LENGTH_LONG).show();
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(MainActivity.this, "解析二维码失败", LENGTH_LONG).show();
                }
            }
        } else if (requestCode == REQUEST_CAMERA_PERM) {
            Toast.makeText(this, "从设置页面返回...", Toast.LENGTH_SHORT)
                    .show();
        }
    }


    /**
     * 显示抓取提示
     */
    private void showProgressDialog(String message) {
        progressDialog = new CustomDialog(this, new CustomDialogListener() {
            @Override
            public void onDialogClosed(int closeType) {

            }
        });
        progressDialog.setView(LayoutInflater.from(this).inflate(R.layout.promt_data_input_layout, null));
        TextView tv_input = (TextView) progressDialog.findId(R.id.tv_input_promt);
        if (tv_input != null) {
            tv_input.setText(message);
        }
        progressDialog.setCanceledOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.show();

        dialogMatchWindow(progressDialog);
    }

    private void dialogMatchWindow(Dialog dialog) {
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);

        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = DisplayUtil.dip2px(300, this.getResources().getDisplayMetrics().density);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);

    }


    private void dialogDismiss(Dialog dialog) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    private void doLogin(String psncard) {
        if (!Utils.checkNetworkIsAvailable()) {
            enterHome();
            return;
        }
        String ip = SharedPreferenceTool.getInstance().getString(AppConstants.IP);
        String port = SharedPreferenceTool.getInstance().getString(AppConstants.PORT);
        if (TextUtils.isEmpty(ip) || TextUtils.isEmpty(port)) {
            Toast.makeText(this, "请先到设置界面初始化IP和端口号!", Toast.LENGTH_SHORT).show();
            return;
        }
        showProgressDialog("登录中...");
        List<SQLOrgPersonBean> psncode = DatabaseUtils.getHelper().queryByArgs(SQLOrgPersonBean.class, "psncard", psncard);
        String name = null;
        if (null == psncode) {
            Toast.makeText(this, "没有匹配到员工账号!", Toast.LENGTH_SHORT).show();
            dialogDismiss(progressDialog);
            return;
        }
        for (SQLOrgPersonBean bean : psncode) {
            name = bean.psnname;
            dept_code = bean.deptcode;
            code = bean.psncode;
            Trace.d("======" + name);
        }

        AppConstants.USER_NAME = name;
        AppConstants.USER_CODE = code;
        AppConstants.DEPT_CODE = dept_code;

        if (App.ALREADY_SYNC) {
            enterHome();
        } else {
            //getData();

            loadBaseData();
        }

//        ActivityStackManager.getInstance().finishActivity(MainActivity.class);
    }


    private void loadBaseData(){
        AsyncTask<Integer,Integer,Integer> asyncTask = new AsyncTask<Integer, Integer, Integer>() {
            String msg = "";
            String status = "";
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                showProgressDialog("抓取NC基础数据中...");
            }

            @Override
            protected Integer doInBackground(Integer... integers) {

                try{
                    callWS(AppConstants.GET_PERSON);
                    //callWS(AppConstants.GET_ASSET_DATA);
                    callWS(AppConstants.GET_ORG_DEPT);
                    callWS(AppConstants.GET_PAM_LOCATION);
                    callWS(AppConstants.GET_PAM_STATUS);
                }catch (ErrorMsgException e){
                    msg = e.msg;
                    status = e.status;
                    return 1;
                }catch (Exception e){
                    return 2;
                }

                return 0;
            }

            @Override
            protected void onPostExecute(Integer integer) {
                super.onPostExecute(integer);
                dialogDismiss(progressDialog);
                if(integer == 0){
                    enterHome();
                }else if(integer == 1){
                    SharedPreferenceTool.getInstance().remove(AppConstants.IP);
                    SharedPreferenceTool.getInstance().remove(AppConstants.PORT);
                    Toast.makeText(MainActivity.this, "同步失败" + status + "原因" + msg, Toast.LENGTH_SHORT).show();
                }else if(integer == 2){
                    SharedPreferenceTool.getInstance().remove(AppConstants.IP);
                    SharedPreferenceTool.getInstance().remove(AppConstants.PORT);
                    Toast.makeText(MainActivity.this, "数据异常", Toast.LENGTH_SHORT).show();
                }
            }
        }.execute();
    }

    private void callWS(final String url) {
        Trace.d("url====" + url);
        //通过工具类调用WebService接口
        LinkedHashMap<String, String> value = WebServiceDataUtils.getParameterData(url, "1=1");
        WebServiceHelper.callWebServiceSynchronized(WebServiceHelper.WEB_URL, AppConstants.METHOD_NAME, value, new WebServiceHelper.WebServiceCallBack() {
            @Override
            public void callBack(SoapObject result) {
                Trace.d("result==" + result);
                if (result != null) {
                    String json = result.getProperty(0).toString();
                    BaseEntity assetBean = JsonParser.deserializeByJson(json, BaseEntity.class);
                    if (assetBean != null) {
                        if (assetBean.isSuccess()) {
                            // do something
                            Trace.d("成功!");
                            switch (url) {
                                case AppConstants.GET_PERSON:
                                    WebPersonEntity webPersonEntity = JsonParser.deserializeByJson(json, WebPersonEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLOrgPersonBean.class);
                                    DatabaseUtils.getHelper().saveAll(webPersonEntity.getOrg_psn());  //组织人员
                                    break;
                                case AppConstants.GET_ASSET_DATA:
                                    WebAssetEntity webAssetEntity = JsonParser.deserializeByJson(json, WebAssetEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLPamAssetBean.class);
                                    DatabaseUtils.getHelper().saveAll(webAssetEntity.getPam_asset()); // 设备
                                    break;
                                case AppConstants.GET_ORG_DEPT:
                                    WebOrgStructureEntity webOrgStructureEntity = JsonParser.deserializeByJson(json, WebOrgStructureEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLOrgStructureBean.class);
                                    DatabaseUtils.getHelper().saveAll(webOrgStructureEntity.getV_org_dept()); //部门
                                    break;
                                case AppConstants.GET_PAM_LOCATION:
                                    WebLocationEntity webLocationEntity = JsonParser.deserializeByJson(json, WebLocationEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLPamLocationBean.class);
                                    DatabaseUtils.getHelper().saveAll(webLocationEntity.getPam_loc()); //位置
                                    break;
                                case AppConstants.GET_PAM_STATUS:
                                    WebPamStatusEntity pamStatusBean = JsonParser.deserializeByJson(json, WebPamStatusEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLPamStatusBean.class);
                                    DatabaseUtils.getHelper().saveAll(pamStatusBean.getPam_sta()); //状态
                                    break;
                            }
                        } else {
                            throw new ErrorMsgException("",assetBean.msg,assetBean.status);
                        }
                    } else {
                        throw new ErrorMsgException("","返回JSON数据格式异常","");
                    }
                }else {
                    if (!Utils.checkNetworkIsAvailable()) {
                        throw new ErrorMsgException("","请检查网络连接情况","");
                    }
                    throw new ErrorMsgException("","IP设置或PORT设置有误,请检查","");
                }
            }
        });
    }


    private void getData() {
        Message message = Message.obtain();
        message.what = 0;
        message.obj = AppConstants.GET_ORG_DEPT;
        //handler.sendMessage(message);
    }

    private CustomDialog progressDialog;
    private String ip;
    private String code;
    private String dept_code;

    private static final int GET_ORG = 0;
    private int count;
    /*private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_ORG:
                    String url = (String) msg.obj;
                    callWS(url);
                    break;
            }
        }
    };

    private void callWS(String url) {
        Trace.d("url====" + url);
        //通过工具类调用WebService接口
        LinkedHashMap<String, String> value = WebServiceDataUtils.getParameterData(url, "1=1");
        WebServiceHelper.callWebService(WebServiceHelper.WEB_URL, AppConstants.METHOD_NAME, value, new WebServiceHelper.WebServiceCallBack() {
            @Override
            public void callBack(SoapObject result) {
                Trace.d("result==" + result);
                if (result != null) {
                    String json = result.getProperty(0).toString();
                    Trace.d("json====" + json);
                    BaseEntity assetBean = JsonParser.deserializeByJson(json, BaseEntity.class);
                    if (assetBean != null) {
                        if (assetBean.isSuccess()) {
                            // do something
                            Trace.d("成功!");
                            count++;
                            Message message = Message.obtain();
                            message.what = 0;
                            switch (count) {
                                case 1:
                                    WebOrgStructureEntity webOrgStructureEntity = JsonParser.deserializeByJson(json, WebOrgStructureEntity.class);
                                    List<SQLOrgStructureBean> v_org_dept = webOrgStructureEntity.getV_org_dept();
                                    if (v_org_dept!= null && v_org_dept.size() > 0) {
                                        DatabaseUtils.getHelper().clear(SQLOrgStructureBean.class);
                                        DatabaseUtils.getHelper().saveAll(v_org_dept);
                                    }
                                    message.obj = AppConstants.GET_PERSON;
                                    break;
                                case 2:
                                    WebPersonEntity webPersonEntity = JsonParser.deserializeByJson(json, WebPersonEntity.class);
                                    List<SQLOrgPersonBean> org_psn = webPersonEntity.getOrg_psn();
                                    if (org_psn!= null && org_psn.size() > 0) {
                                        DatabaseUtils.getHelper().clear(SQLOrgPersonBean.class);
                                        DatabaseUtils.getHelper().saveAll(org_psn);
                                    }
                                    message.obj = AppConstants.GET_PAM_LOCATION;
                                    break;
                                case 3:
                                    WebLocationEntity webLocationEntity = JsonParser.deserializeByJson(json, WebLocationEntity.class);
                                    List<SQLPamLocationBean> pam_loc = webLocationEntity.getPam_loc();
                                    if (pam_loc!= null && pam_loc.size() > 0) {
                                        DatabaseUtils.getHelper().clear(SQLPamLocationBean.class);
                                        DatabaseUtils.getHelper().saveAll(pam_loc);
                                    }
                                    message.obj = AppConstants.GET_PAM_STATUS;
                                    break;
                                case 4:
                                    WebPamStatusEntity pamStatusBean = JsonParser.deserializeByJson(json, WebPamStatusEntity.class);
                                    List<SQLPamStatusBean> pam_sta = pamStatusBean.getPam_sta();
                                    if (pam_sta!= null && pam_sta.size() > 0) {
                                        DatabaseUtils.getHelper().clear(SQLPamStatusBean.class);
                                        DatabaseUtils.getHelper().saveAll(pam_sta);
                                    }
                                    enterHome();
                                    break;
                            }
                            if (count >= 4) {
                                return;
                            }
                            handler.sendMessage(message);
                        } else {
                            dialogDismiss(progressDialog);
                            enterHome();
                            Toast.makeText(MainActivity.this, "失败" + assetBean.status + "原因" + assetBean.msg, Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    dialogDismiss(progressDialog);
                    enterHome();
                    if (Utils.checkNetworkIsAvailable()) {
                        Toast.makeText(MainActivity.this, "网络请求失败!", Toast.LENGTH_SHORT).show();
                    }
                }

            }
        });
    }*/

    private void enterHome() {
        Intent intent = new Intent(this, HomeActivity.class);
        startActivity(intent);
        finish();

    }


    /**
     * 资产盘点
     */
    private void doCheckAssets() {
        Intent intent = new Intent(this, CheckAssetsActivity.class);
        startActivity(intent);
        finish();
    }
}
